package com.mc.wsdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 监听websockert地址/myWs
 * @author ye.renyun
 */
@ServerEndpoint("/myWs")
@Component
@Slf4j
public class WsServerEndpoint {
    // 线程安全的
    static Map<String,Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 连接建立时执行的操作
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        sessionMap.put(session.getId(),session);
        log.info("websocket is open:{}",session.getId());
    }

    /**
     * 收到了客户段消息执行的操作
     * @param text
     * @return
     */
    @OnMessage
    public String onMessage(String text){
        log.info("收到了一条消息：{}",text);
        return "已经收到你的消息";
    }

    /**
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session){
        sessionMap.remove(session.getId());
        log.info("websocket is close!");
    }
    /**
     * 每隔2000MS=2S执行一次：每2S发送给客户端心跳消息
     */
    @Scheduled(fixedRate = 2000)
    public void sendMsg()   {
        for (Map.Entry<String, Session> entry : sessionMap.entrySet()) {
            Session value = entry.getValue();
            try {
                value.getBasicRemote().sendText("心跳！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
